import axios from 'axios'
import { publicIp } from './apiIp'
// import {LOGIN} from './apiURL'
import { message } from 'antd'
import store from 'store'
import '@/utils/bane'
import base64 from '../utils/base64'
import { UniteAPi } from '@/utils/Unite'
import { cond } from 'lodash'
let hide = null
let base = new base64()
// let url = "https://192.168.12.53" //
const instance = axios.create({
  //创建axios实例，在这里可以设置请求的默认配置
  timeout: 30000, // 设置超时时间10s
  baseURL: publicIp + '/gw/1.0/', //根据自己配置的反向代理去设置不同环境的baeUrl
  withCredentials: false, // 允许携带cookie
  retry: 2,
  retryDelay: 1000, //设置全局请求间隔
})
// 文档中的统一设置post请求头。下面会说到post请求的几种'Content-Type'
instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.get['Content-Type'] = 'application/json'

// instance.defaults.withCredentials=true
let httpCode = {
  //这里我简单列出一些常见的http状态码信息，可以自己去调整配置
  400: '请求参数错误',
  401: '权限不足, 请重新登录',
  403: '服务器拒绝本次访问',
  404: '请求资源未找到',
  500: '内部服务器错误',
  501: '服务器不支持该请求中使用的方法',
  502: '请稍后重试',
  504: '网关超时',
}
if (sessionStorage.getItem('loginName') != null) {
  document.cookie = 'loginName=' + sessionStorage.getItem('loginName')
}
function download(content, fileName) {
  const blob = new Blob([content]) //创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
  const url = window.URL.createObjectURL(blob) //URL.createObjectURL(object)表示生成一个File对象或Blob对象
  let dom = document.createElement('a') //设置一个隐藏的a标签，href为输出流，设置download
  dom.style.display = 'none'
  dom.href = url
  dom.setAttribute('download', fileName) //指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
  document.body.appendChild(dom)
  dom.click()
}
function chineseToUtf8(str) {
  var i, len, ch
  const arr = []
  len = str.length
  for (i = 0; i < len; i++) {
    ch = str.charCodeAt(i)
    if (ch <= 0x7f) {
      arr.push(str.charAt(i))
    } else if (ch <= 0x7ff) {
      arr.push(String.fromCharCode(0xc0 | (ch >> 6 < 0xff), 0x80 | (ch < 0x3f)))
    } else if (
      0xd800 == (ch & 0xfc00) &&
      i + 1 < len &&
      0xdc00 == (str.charCodeAt(i + 1) & 0xfc00)
    ) {
      // Surrogate pair: U+10000 to U+10FFFF
      i++
      ch = 0x10000 + ((ch & 0x03ff) << 10) + (str.charAt(i) & 0x03ff)
      arr.push(
        String.fromCharCode(
          0xf0 | (ch >> 18 < 0xff),
          0x80 | (ch >> 12 < 0x3f),
          0x80 | (ch >> 6 < 0x3f),
          0x80 | (ch < 0x3f)
        )
      )
    } else {
      arr.push(
        String.fromCharCode(
          0xe0 | (ch >> 12 < 0xff),
          0x80 | (ch >> 6 < 0x3f),
          0x80 | (ch < 0x3f)
        )
      )
    }
  }
  return arr.join('')
}
let arr = [
  'info?sectionPath=QUERY,delivery',
  'info?sectionPath=QUERY,mail',
  'action?command=riskmail',
  'action?command=risktrend',
  'action?command=risktype',
  'action?command=riskstat',
  'action?command=transstat',
  'info?sectionPath=QUERY,gwpassmail',
  'info?sectionPath=QUERY,gwmailevent',
  'home/get_img',
]
let UniteA = [
  'info?sectionPath=QUERY,delivery',
  'info?sectionPath=QUERY,mail',
  'action?command=riskmail',
  'action?command=risktrend',
  'action?command=risktype',
  'action?command=riskstat',
  'action?command=transstat',
  'info?sectionPath=QUERY,gwpassmail',
  'info?sectionPath=QUERY,gwmailevent',
  'home/msg',
  'em/get_usr_em',
  'em/get_all',
  'action?command=queryserialnum',
]
/** 添加请求拦截器 **/
instance.interceptors.request.use(
  (config) => {
    var timeNew = new Date().valueOf()
    var timeout = sessionStorage.getItem('timeout')
    var timestamp = sessionStorage.getItem('timestamp')
    config.url = UniteAPi(config.url)
    config.headers['token'] = sessionStorage.getItem('token') || ''
    config.headers['Content-Type'] = 'application/json'
    if (sessionStorage.getItem('token')) {
      let arr = 'admin:' + sessionStorage.getItem('Basename')
      let nane = base.encode(arr)
      config.headers['Authorization'] =
        'token ' + sessionStorage.getItem('token')
    }
    // hide = message.loading({content: 'Loading...', duration: 0});
    // 在这里：可以根据业务需求可以在发送请求之前做些什么:例如我这个是导出文件的接口，因为返回的是二进制流，所以需要设置请求响应类型为blob，就可以在此处设置。
    if (config.url.includes('pur/contract/export')) {
      config.headers['responseType'] = 'blob'
    }
    // 我这里是文件上传，发送的是二进制流，所以需要设置请求头的'Content-Type'
    if (config.url.includes('pur/contract/upload')) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error)
  }
)

/** 添加响应拦截器  **/
instance.interceptors.response.use(
  (response) => {
    // hide()
    const res = response.data
    if (response.config.responseType === 'blob') {
      return response
    }
    if (response.status == '200') {
      // 响应结果里的statusText: ok是我与后台的约定，大家可以根据实际情况去做对应的判断
      return Promise.resolve(response.data)
    } else if (response.status == '300') {
      message.error('用户存在')
      return Promise.reject(response.data.message)
    } else if (response.status == '400') {
      message.error('响应超时')
      return Promise.reject(response.data.message)
    } else if (response.status == '201') {
      message.error(response.data.error)
      return Promise.reject(response.data.message)
    }
  },
  (error) => {
    // hide()
    if (error.response) {
      // 根据请求失败的http状态码去给用户相应的提示
      if (error.response.status === 401) {
        let data = {
          refreshtoken: sessionStorage.getItem('refreshtoken'),
        }
        post('/authorize/password/update', data).then((res) => {
          sessionStorage.setItem('token', res.token)
        })
        // return Promise.resolve(error.response.status)
      }
      if (error.response.status === 402) {
        message.error('长时间未操作,请重新登录')
        sessionStorage.removeItem('Theuser')
        sessionStorage.removeItem('timeout')
        sessionStorage.removeItem('routeList')
        sessionStorage.removeItem('permissions')
        sessionStorage.removeItem('user')
        sessionStorage.removeItem('isInit')
        sessionStorage.removeItem('openKeys')
        sessionStorage.removeItem('Permission')
        location.reload()
      }
      var config = error.config
      config._retryCount = config._retryCount || 0
      // 如果当前发送的请求大于等于设置好的请求次数时，不再发送请求，返回最终的错误信息
      if (config._retryCount >= 1) {
        return Promise.reject(error)
      }
      config._retryCount += 1
      // //超时处理 error.config是一个对象，包含上方create中设置的三个参数
      setTimeout(() => {
        var config = error.config
        config.headers.Authorization =
          'token ' + sessionStorage.getItem('token')
        // 设置请求间隔 在发送下一次请求之前停留一段时间，时间为上方设置好的请求间隔时间
        var backoff = new Promise(function (resolve) {
          setTimeout(function () {
            resolve()
          }, config.retryDelay || 1)
        })
        if (error.response.status === 500) {
        } else {
          // // 再次发送请求
          return backoff.then(function () {
            return instance(config)
          })
        }
      }, 1500)
    } else {
      console.log(error)
      return Promise.reject('请求超时, 请刷新重试')
    }
  }
)
/* 统一封装get请求 */
export const get = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url: url,
      params: data,
      ...config,
    })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        console.log(error)
        reject(error)
      })
  })
}

/* 统一封装post请求  */
export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 下载更新  */
export const downlopost = (url, fileName, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url: url,
      data,
      responseType: 'blob', //服务器返回的数据类型
    })
      .then((response) => {
        const content = response.data //返回的内容
        const fileName = response.headers.filename //文件名
        download(content, base.decode(fileName))
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求  */
export const postD = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      responseType: 'blob',
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求  */
export const put = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'put',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        resolve(response)
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          global.constants.apply = 1
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装*/
export const Delete = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'Delete',
      url: url,
      data,
      ...config,
    })
      .then((response) => {
        let bol = arr.every((item) => url.indexOf(item) === -1)
        if (bol) {
          // window.temp = 0
          global.constants.apply = 1
        }
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
/* 统一封装post请求上传  */
export const Update = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data,
      timeout: 10000 * 6 * 10,
      ...config,
    })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
